@extends("layouts.backend.webadmin")
@section('page-header')
<h1>
    <small>ogz</small>
</h1>
@endsection

@section('content')
<link rel="stylesheet" href="{{env('APP_ROOT')}}/assets/jquery-treetable/css/jquery.treetable.css">
<link rel="stylesheet" href="{{env('APP_ROOT')}}/assets/select2/css/select2.min.css">
<link rel="stylesheet" href="{{env('APP_ROOT')}}/assets/select2/css/select2totree.css">
<!-- Main content -->
<section class="content">
    <div class="row">
        <div class="col-xs-12">

            <div class="box">
                <!--<div class="box-header">
                    <h3 class="box-title btn btn-primary add-row ogz-add">增加</h3>
                </div>-->
                <!-- /.box-header -->
                <div class="box-body">
                    <table id="ogz-list" class="table table-bordered table-striped">
                        <thead>
                        <tr>

                        </tr>
                        </thead>

                        <tbody>
                        </tbody>
                    </table>
                </div>
                <!-- /.box-body -->
            </div>
            <!-- /.box -->
        </div>
        <!-- /.col -->
    </div>
    <!-- /.row -->
</section>
<form id="add-form">
    <section id="add" style="display: none;" class="content">
            <input type="hidden" name="id">
            <div class="form-group">
                <label for="parent-ogz">父级栏目</label><br/>
                <select class="form-control" id="parent-ogz" name="pid" style="width: 100%">
                    <!--<option class="l1 non-leaf" value="0">--选择父级菜单--</option>-->
                </select>
            </div>
            <div class="form-group">
                <label for="name">名称</label>
                <input type="text" class="form-control" id="name" placeholder="组织机构" name="name">
            </div>
            <div id="sort-order" style="display: none;" class="form-group">
                <label for="sort">排序</label>
                <input type="text" class="form-control" id="sort" placeholder="排序" name="sort">
            </div>
            <div class="form-group">
                <label for="description">描述</label>
                <input type="text" class="form-control" id="description" placeholder="描述" name="description">
            </div>

            <div class="form-group">
                <label for="parent-user">联系人</label>
                <select style="width: 100%;" multiple="multiple" class="form-control user-multiple" id="parent-user" name="user_id[]">
                    <!--<option value="0">--选择联系人--</option>-->
                </select>
            </div>
            <button id="submit-data" type="button" class="btn btn-primary">确认</button>
    </section>
</form>
<input type="hidden" name="ogzs" value="{{$ogzs}}">
<input type="hidden" name="users" value="{{$users}}">
<input type="hidden" name="links" value="{{$links}}">
@stop
@section('javascript-end')
<script src="{{env('APP_ROOT')}}/assets/layui/layui.all.js"></script>
<script src="{{env('APP_ROOT')}}/assets/jquery-treetable/js/jquery.treetable.js"></script>
<script src="{{env('APP_ROOT')}}/assets/select2/js/select2.min.js"></script>
<script src="{{env('APP_ROOT')}}/assets/select2/js/select2totree.js"></script>
<script src="{{env('APP_ROOT')}}/assets/select2/js/i18n/zh-CN.js"></script>
<script src="{{env('APP_ROOT')}}/js/common.js"></script>
<script>
    $(function () {
        var m1 = manage();
        //加载基本项
        //组织机构
        var ogzs = $.parseJSON($('input[name="ogzs"]').val());
        //联系人
        var users = $.parseJSON($('input[name="users"]').val());
        //多选联系人
        $('.user-multiple').select2();
        //添加
        $('.box-body').on('click','button.add-row',function(){
            //排序字段
            $('#sort-order').hide();
            //reset表单
            $("#add-form")[0].reset();
            //清除隐藏域的值
            $(':input[type="hidden"]').val('');
            //更新提交按钮
            $("#submit-data2").attr('id','submit-data');
            //添加层
            addLayer = layer.open({
                title:'新增组织机构',
                zIndex:10,
                type:1,
                content:$("#add"),
                end:function(){
                    $('#add').hide();
                },
                success:function() {
                    //select ogz
                    $('#parent-ogz').html(m1.eachSelect(ogzs,'ogz',''));
                    //select tree
                    $('#parent-ogz').select2ToTree({language:'zh-CN'});
                    //select user
                    $('#parent-user').html(m1.eachSelect(users,'user',''));

                }
            });
            //todo 1.on事件里出现重复提交bug 2.token二次提交没有验证,测试处理说明
            $('#add').on( 'click', 'button#submit-data', function () {
                var fields = $("#add-form").serializeArray();
                $.ajax(
                    {
                        url:"{{route('admin.ogz.add')}}",
                        method:"POST",
                        data:fields,
                        headers:{'X-CSRF-TOKEN' : $('meta[name="csrf-token"]').attr('content')},
                    }
                ).done(function(data){
                    getToken();
                    if(data.code===0){
                        //避免跳转出现浮框
                        $('#add').hide();
                        layer.close(layer.index);
                        //刷新table跳转到首页
                        // tables.ajax.reload();
                        //刷新当前页
                        window.location.reload();
                        layer.msg('操作成功');
                    } else {
                        layer.msg(data.msg);
                    }
                }).fail(function (data) {
                    $.each(data.responseJSON, function (key, value) {
                        var input = '#add-form input[name=' + key + ']';

                        // $(input).css("border","1px solid red");
                        layer.msg(value[0]);
                        return false;
                    });

                });
            });
        });
        var tables = $('#ogz-list').DataTable({
            //调整结构
            "dom": '<"dataTables_filter">rti',
            "autoWidth":true,
            //国际化
            'oLanguage'   :{
                'sUrl'    : '{{env("APP_ROOT")}}/assets/bootstrap/js/zh_cn.json'
            },
            "initComplete": function( settings, json ) {
                var button = '<button class="btn btn-primary add-row ogz-add" style="float: left;">增加</button>';
                $('.dataTables_filter').html(button);
                var _$this = this;

                m1.filter(jQuery,true,_$this,false);
            },
            "paging": false, // 禁止分页
            "bSort": false,//禁止排序
            "processing": true,
            //开启服务器模式
            serverSide: true,
            ajax: {
                //指定数据源
                url: "{{route('admin.ogz.search')}}",
                type: "GET",
                data: function(d){
                    delete d.columns;
                    return d;
                },
                //接受服务器数据
                dataSrc:function(json){
                    getToken();
                    return json.data;
                }
            },
            //data值对应数据库字段名
            columns: [
                {
                    'title':'名称',
                    "data": "name",
                    "render": function(data,type,row,meta){

                        if(row.hasChild){
                            return '<i class="fa fa-caret-down" aria-hidden="true"></i>'+data;
                        }else{
                            return data;
                        }
                    },
                    "width":"400px"
                },
                /*{
                    'title':'描述',
                    "data": "description"
                },*/
                {
                    'title':'联系人',
                    "data": "user_name"

                },
                {
                    'title':'增加时间',
                    "data": "created_at"
                },
                {
                    'title':'更新时间',
                    "data": "updated_at"
                },
                {
                    "title":"操作",
                    "targets": -2,
                    "data": null,
                    "render": function(data,type,row,meta){
                        var links = $.parseJSON($('input[name="links"]').val());
                        if($.inArray(row.id,links.ogzs.child) != -1){
                            var button = m1.button('ogz');
                            if(row.deleted_at != null){
                                button1 = button[2];
                            }else{
                                button1 = button[1];
                            }
                            return button[0] +"&nbsp"+ button1;
                        }else{
                            return '';
                        }
                    },
                    "width":"120px"
                }],
            //所有列过滤xss
            columnDefs: [{
                "targets": "_all",
                "render": $.fn.dataTable.render.text()
            }],
            //自定义行属性
            fnRowCallback: function(nRow, aData, iDataIndex,oSettings) {
                $(nRow).attr('data-tt-id',aData.id);
                $(nRow).attr('data-tt-parent-id',aData.pid);

                /*if(aData.pid ==0){
                    $(nRow).attr('class','expanded branch');
                }else{
                    $(nRow).attr('class','expanded leaf');
               }
                var val = aData.level *19;
                $(nRow).find("td").eq(0).prepend('<span class="indenter" style="padding-left: '+val+'px;"></span>');*/

            },
            //绘制完毕回掉函数
            fnDrawCallback: function(oSettings) {
                $('#ogz-list').treetable('destroy');
                var option = {
                    "expandable":true,
                    "initialState":"expanded",
                    "clickableNodeNames":true
                };
                //treeTable
               $('#ogz-list').treetable(option);
            },
            //解决不分页，显示分页信息（默认一页10条，页码总数错误的问题）
            "fnInfoCallback": function (oSettings, iStart, iEnd, iMax, iTotal, sPre) {

                return '当前第 1 页，共 1 页，总条数 ' + iTotal;

            }
        });
        //编辑赋值
        $('#ogz-list tbody').on( 'click', 'button#editrow', function () {
            //排序字段
            $('#sort-order').show();
            //更改添加按钮id
            $('#submit-data').attr('id','submit-data2');
            var data = tables.row($(this).parents('tr')).data();
            var fields = $("#add-form").serializeArray();

            jQuery.each( fields, function(i, field){
                //select
                $(":input[name='id']").val(data.id);
                $(":input[name='sort']").val(data.sort);
                var _name = $.trim(data.name);
                $(":input[name='name']").val(_name.replace(/\├─/g,''));

                $(":input[name='description']").val(data.description);
            });
            //显示编辑
            editLayer = layer.open({
                    title:'修改组织机构',
                    zIndex:10,
                    type:1,
                    content:$("#add"),
                    cancel:function(){
                        // window.location.reload();
                        $('#add').hide();
                    },
                    success:function() {
                        //select ogz
                        $('#parent-ogz').html(m1.eachSelect(ogzs,'ogz',data.pid));
                        //select tree
                        $('#parent-ogz').select2ToTree({language: "zh-CN"});
                        //select user
                        // $('#parent-user').html(m1.eachSelect(users,'user',data.user_id));
                        $('#parent-user').html(m1.eachSelect(users,'user',data.many_user));
                    }
            });

        });
        //编辑提交
        $('#add').on( 'click', 'button#submit-data2', function () {
            fields = $("#add-form").serializeArray();
            $.ajax(
                {
                    url:"{{route('admin.ogz.update')}}",
                    method:"POST",
                    data:fields,
                    headers:{'X-CSRF-TOKEN' : $('meta[name="csrf-token"]').attr('content')}
                }
            ).fail(function(data){
                $.each(data.responseJSON, function (key, value) {
                    var input = '#add-form input[name=' + key + ']';

                    // $(input).css("border","1px solid red");

                    layer.msg(value[0]);
                    return false;

                });
            }).done(function(data){
                if(data.code===0){
                    //避免跳转出现浮框
                    $('#add').hide();
                    getToken();
                    layer.msg('修改成功');
                    //关闭弹窗
                    layer.close(editLayer);
                    //刷新table跳转到首页
                    // tables.ajax.reload();
                    window.location.reload();
                }else{
                    layer.msg(data.msg);
                }
            });
        });
        //禁用
        $('#ogz-list tbody').on( 'click', 'button#delrow', function () {
            var data = tables.row($(this).parents('tr') ).data();
            m1.delete(jQuery,layer,"{{route('admin.ogz.delete')}}",data);
        });
        //启用
        $('#ogz-list tbody').on( 'click', 'button#activerow', function () {
            var data = tables.row($(this).parents('tr') ).data();
            m1.active(jQuery,layer,"{{route('admin.ogz.active')}}",data);
        });
    });
</script>
@endsection
